package org.seckill.service.impl;

import org.apache.commons.collections.MapUtils;
import org.seckill.Exception.RepeatKillException;
import org.seckill.Exception.SeckillCloseException;
import org.seckill.Exception.SeckillException;
import org.seckill.common.Const;
import org.seckill.dao.SeckillMapper;
import org.seckill.dao.SuccessKilledMapper;
import org.seckill.dao.cache.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.service.ISeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author Elmer
 * @create 2017-07-30 11:53
 * @desc ISeckillService 实现类
 **/
@Service
public class SeckillServiceImpl implements ISeckillService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private SuccessKilledMapper successKilledMapper;
    @Autowired
    private RedisDao redisDao;

    private static final String salt = "drynhunefw796saH90QWE?>ASD";

    @Override
    public List<Seckill> getSeckillList() {
        return seckillMapper.queryAll(0, 10);
    }

    @Override
    public Seckill getById(Long seckillId) {
        //return seckillMapper.selectByPrimaryKey(seckillId);

        //redis方式获取seckill
        Seckill seckill = redisDao.getSeckill(seckillId);
        if (seckill == null) {
            //redis缓存中没有seckill对象
            seckill = seckillMapper.selectByPrimaryKey(seckillId);
            if (seckill != null) {
                //放入redis缓存
                redisDao.putSeckill(seckill);
            }
            return seckill;
        } else {
            return seckill;
        }
    }

    @Override
    @Transactional
    /**
     * 使用注解控制事务方法的优点：
     * 1，开发团队达成一致约定，明确标注事务方法的编程风格
     * 2，保证事务方法的执行时间尽可能短，不要穿插其他的网络操作（RPC/HTTP请求 或者剥离到事务的方法外部）
     * 3，不是所有的方法搜需要事务，如只有一条修改操作，只读操作不需要事务控制
     */
    public Exposer exportSeckillURL(Long seckillId) {
        //缓存优化

        //md5盐值
        Seckill seckill = seckillMapper.selectByPrimaryKey(seckillId);
        if (seckill == null) {
            return new Exposer(false, seckillId);
        }
        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }
        String md5 = getMD5(seckillId);
        return new Exposer(seckillId, md5, true);
    }

    @Override
    public SeckillExecution executeSeckill(Long seckillId, Long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            throw new SeckillException("seckill data rewrite");
        }
        //执行秒杀逻辑：减库存+记录购买行为
        Date nowTime = new Date();
        try {
            //记录购买行为
            int insertCount = successKilledMapper.insetSuccessKilled(seckillId, userPhone);
            if (insertCount <= 0) {
                //重复秒杀
                throw new RepeatKillException("seckill repeated");
            } else {
                //减库存，热点商品竞争
                int updateCpunt = seckillMapper.reduceNumber(seckillId, nowTime);
                if (updateCpunt <= 0) {
                    //没有更新到记录，秒杀结束，rollback
                    throw new SeckillCloseException("seckill is closed");
                } else {
                    //秒杀成功，commit
                    SuccessKilled successKilled = successKilledMapper.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, Const.SeckillStatusEnum.KILL_SUCCESS, successKilled);
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatKillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //所有编译期异常转化为运行期异常
            throw new SeckillException("seckill inner error" + e.getMessage());
        }

    }

    @Override
    public SeckillExecution executeSeckillProcedure(Long seckillId, Long userPhone, String md5) {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            return new SeckillExecution(seckillId, Const.SeckillStatusEnum.DATA_REWRITE);
        }
        Date nowTime = new Date();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("seckillId", seckillId);
        map.put("phone", userPhone);
        map.put("killTime", nowTime);
        map.put("result", null);

        //执行存储过程，result被复制
        try {
            successKilledMapper.killByProcedure(map);
            //获取result
            int result = MapUtils.getInteger(map, "result", -2);
            if (result == 1) {
                SuccessKilled successKilled = successKilledMapper.queryByIdWithSeckill(seckillId, userPhone);
                return new SeckillExecution(seckillId, Const.SeckillStatusEnum.KILL_SUCCESS, successKilled);
            } else {
                return new SeckillExecution(seckillId, Const.SeckillStatusEnum.statusOf(result));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new SeckillExecution(seckillId, Const.SeckillStatusEnum.INNER_ERROR);
        }
    }

    /**
     * MD5
     *
     * @param seckillId
     * @return
     */
    private String getMD5(long seckillId) {
        String base = seckillId + "/" + salt;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }
}
